<template>
  <div>
    <div class="add">
      <el-card class="lh28">
        <div class="addOrderPopout scrollbar">
          <!-- <div class="titleL">基本信息</div> -->
          <el-form ref="detail" :model="detail" :rules="rules" label-width="120px">
            <el-form-item size="mini" label="角色属性">
              <el-radio-group v-model="detail.isHeadquarters" :disabled="nameType != '新增'" @change="changeHeadquarters">
                <el-radio :label="1">总部</el-radio>
                <el-radio :label="0">院区</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item size="mini" label="角色名称" prop="name">
              <el-input v-model="detail.name" class="w280" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item v-if="detail.isHeadquarters == 0" size="mini" label="适用院区" prop="fitDepts">
              <el-select v-model="detail.fitDepts" multiple clearable class="w280" placeholder="请选择">
                <el-option v-for="item in options.yard" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="detail.isHeadquarters == 1" size="mini" label="适用组织" prop="fitDepts">
              <el-cascader
                ref="fitDepts"
                v-model="detail.fitDepts"
                class="w280"
                collapse-tags
                :options="options.dept"
                :show-all-levels="false"
                :props="optionProps"
                clearable
              />
            </el-form-item>

            <el-form-item size="mini" label="数据范围" class="range">
              <el-radio-group v-model="detail.dataScope">
                <el-radio :label="0">全组织</el-radio>
                <el-radio :label="1">本部门和下级部门</el-radio>
                <el-radio :label="2">本部门</el-radio>
                <el-radio :label="3">本人和下级部门</el-radio>
                <el-radio :label="4">特定部门</el-radio>
                <el-radio :label="5">本人</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="detail.dataScope == 4" size="mini" label="选择部门" prop="selectDepts">
              <el-cascader
                v-model="detail.selectDepts"
                class="w280"
                collapse-tags
                :options="options.dept"
                :show-all-levels="false"
                :props="optionProps"
                clearable
              />
            </el-form-item>
          </el-form>
          <div class="flex_sb tabBox hand mt10 mb10">
            <div :class="(active ==1?'active':'')" @click="clickTab(1)">页 面 权 限</div>
            <div :class="(active ==2?'active':'')" @click="clickTab(2)">数 据 权 限</div>
          </div>
          <div v-show="active ==1 && pageJurisdiction.length>0">
            <div class="flex_sb pl10 pr10">
              <div class="distribution">分配权限：<span>(将会在以上管理范围内配置权限)</span></div>
              <el-checkbox v-model="checked" @change="clickAll">全部权限</el-checkbox>
            </div>
            <div class="rollBox">
              <!-- default-expand-all -->
              <el-tree
                ref="tree"
                :data="pageJurisdiction"
                show-checkbox
                node-key="id"
                :props="menuProps"
                @check="currentCheckedPage"
              />
              <!-- :default-checked-keys="detail.showMenus" -->
              <!-- :default-checked-keys="detail.showMenus" -->
            </div>
          </div>
          <div v-show="active ==2 && dataPermission.length>0">
            <div class="flex_sb pl10 pr10">
              <div class="distribution">分配权限：<span>(将会在以上管理范围内配置权限)</span></div>
              <el-checkbox v-model="checkedData" @change="clickAllData">全部权限</el-checkbox>
            </div>
            <div class="rollBox">
              <el-tree
                ref="treeData"
                :data="dataPermission"
                show-checkbox
                node-key="id"
                :props="dataProps"
                @check="currentCheckedData"
              />
            </div>
          </div>
          <div class="footer">
            <el-button v-if="nameType != '详情'" type="primary" size="small" @click="createDetail('detail')">提
              交</el-button>
            <el-button size="small" @click="returnUpper">返 回</el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>

import { getDeptTree } from '@/api/organization';
import { yardPullList } from '@/api/courtyardAdmin';
import { tablelist } from '@/api/system';
import { getMenuTree } from '@/api/menu';
import { rolesAdd, rolesDetail, rolesUpdate } from '@/api/role';
class Detail {
  isHeadquarters = 1;
  name = '';
  yard = '';
  dataScope = 0;
  fitDepts = [];
  selectDepts = [];
  hiddenTableFields = [];
  showMenus = [];
  isDrugSystem = 1;
}

class Rules {
  name = [{ required: true, message: '请输入角色名称', trigger: 'blur' }];
  fitDepts = [{ required: true, message: '请选择适用组织', trigger: 'change' }];
  yard = [{ required: true, message: '请选择所属院区', trigger: 'change' }];
  selectDepts = [{ required: true, message: '请选择部门', trigger: 'change' }];
}
class Options {
  dept = []
  yard = []
  options = [
    { id: 1, name: '选项一' },
    { id: 2, name: '选项二' },
    { id: 3, name: '选项三' },
    { id: 4, name: '选项四' }
  ];
  type = [
    { id: 1, name: '推广院' },
    { id: 2, name: '医养院' },
    { id: 3, name: '平台院' },
    { id: 4, name: '药局' }
  ];
}
export default {
  name: 'CourtyardAdminDetail',
  data() {
    return {
      detail: new Detail(), // 表单
      options: new Options(), // 选项
      rules: new Rules(), // 表单校验
      checked: false, // 所有页面权限
      checkedData: false, // 所有数据权限
      active: 1,
      nameType: '详情',
      fitDepts: [],
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        multiple: true,
        checkStrictly: true,
        emitPath: false
      },
      pageJurisdiction: [],
      dataPermission: [],
      checkedKeys: [1],
      checkedKeysData: [],
      menuProps: {
        children: 'children',
        label: 'name'
      },
      dataProps: {
        children: 'fieldsList',
        label: 'name'
      }
    };
  },
  mounted() {
    // console.log(this.$route.query.nameType);
    this.nameType = this.$route.query.nameType;
    // this.getUeserDetail();
    this.getOptions(1);
  },
  methods: {
    async getUeserDetail() {
      // let id = getToken('session_id');
      // const { data } = await ueserDetail({ id: id });
      // let deptList = data.deptList.map((i) => {
      //   return i.id;
      // });
    },

    async getOptions(type) {
      try {
        const { data } = await getDeptTree({
          withOutAutoCreate: false,
          filterOtherDept: 0
        });
        let dept = this.getTreeData(data);
        this.options.dept = dept.length > 0 ? dept : [];
      } catch (e) {
        this.options.dept = [];
      }

      const dataPermission = await tablelist();
      this.dataPermission = dataPermission ? dataPermission.data : [];
      this.dataPermission.forEach((item, index) => {
        item.name = item.name + '(勾选隐藏)';
      });

      const yard = await yardPullList({});
      this.options.yard = yard ? yard.data : [];
      // console.log(this.pageJurisdiction);
      let isHeadquarters = 1;
      if (this.nameType != '新增') {
        isHeadquarters = this.$route.query.isHeadquarters;
      }
      const menuPermission = await getMenuTree({ isHeadquarters, clientType: 0 });
      this.pageJurisdiction = menuPermission ? menuPermission.data : [];
      if (this.nameType != '新增') {
        this.getDetail();
      }
    },
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // 最后一级没有数据将children变成undefined
          data[i].children = undefined;
        } else {
          // children不为空时继续调用该方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    // 获取详情
    async getDetail() {
      const { data } = await rolesDetail({ id: this.$route.query.id });
      this.detail = data;
      this.detail.isHeadquarters = data.isHeadquarters ? 1 : 0;
      let childList = [];
      let forEachPageJurisdiction = function(item) {
        item.forEach(ele => {
          if (!ele.children || ele.children.length == 0) {
            childList.push(ele.id);
          } else {
            forEachPageJurisdiction(ele.children);
          }
        });
      };
      forEachPageJurisdiction(this.pageJurisdiction);
      let checkedKeys = [];
      this.detail.showMenus.forEach(ele => {
        if (childList.indexOf(ele) >= 0) {
          checkedKeys.push(ele);
        }
      });
      console.log(checkedKeys);
      this.$refs.tree.setCheckedKeys(checkedKeys);

      let childTabList = [];
      let forEachDataPermission = function(item) {
        item.forEach(ele => {
          if (!ele.fieldsList || ele.fieldsList.length == 0) {
            childTabList.push(ele.id);
          } else {
            forEachDataPermission(ele.fieldsList);
          }
        });
      };
      forEachDataPermission(this.dataPermission);

      let tabCheckedKeys = [];
      this.detail.hiddenTableFields.forEach(ele => {
        if (childTabList.indexOf(ele) >= 0) {
          tabCheckedKeys.push(ele);
        }
      });
      this.$refs.treeData.setCheckedKeys(tabCheckedKeys);
      // this.detail.fitDepts = data.fitDepts.split(',');
      // this.detail.hiddenTableFields = data.hiddenTableFields.split(',');
      // this.detail.showMenus = data.showMenus.split(',');
      // this.detail.selectDepts = data.selectDepts.split(',');
      // console.log(data);
    },
    // 切换页面/数据权限
    async clickTab(val) {
      this.active = val;
      // this.getOptions(this.active);
    },
    // 选择角色属性
    async changeHeadquarters(e) {
      this.detail = new Detail();
      this.detail.isHeadquarters = e;
      const menuPermission = await getMenuTree({ isHeadquarters: this.detail.isHeadquarters });
      this.pageJurisdiction = menuPermission ? menuPermission.data : [];
    },
    // 全部页面权限
    clickAll() {
      if (this.checked) {
        // // this.checkedKeys = [1, 80];
        // let checkedPage = [];
        // this.treeIterator(this.pageJurisdiction, (node) => {
        //   // console.log(node.name, node.id);
        //   checkedPage.push(node.id);
        // });
        // this.detail.showMenus = checkedPage;
        // console.log(this.detail.showMenus);
        this.$refs.tree.setCheckedNodes(this.pageJurisdiction);
      } else {
        // this.detail.showMenus = [];
        // this.checkedKeys = [];
        this.$refs.tree.setCheckedNodes([]);
        // this.$set(this.checkedKeys, [1]);
      }
      // console.log(this.checkedKeys);
    },
    // 全部数据权限
    clickAllData() {
      if (this.checkedData) {
        // let checkedData = [];
        // this.dataPermission.forEach((item) => {
        //   item.fieldsList.forEach((val) => {
        //     checkedData.push(val.id);
        //   });
        // });
        // this.detail.hiddenTableFields = checkedData;
        this.$refs.treeData.setCheckedNodes(this.dataPermission);
        // console.log(this.detail.hiddenTableFields);
      } else {
        this.$refs.treeData.setCheckedNodes([]);
        // this.$set(this.checkedKeysData, [1]);
      }
      // console.log(this.checkedKeysData);
    },
    treeIterator(tree, func) {
      tree.forEach((node) => {
        func(node);
        node.children && this.treeIterator(node.children, func);
      });
    },

    // 页面权限更改
    currentCheckedPage(nodeObj, SelectedObj) {
      // console.log(SelectedObj.checkedKeys);
      // this.detail.showMenus = SelectedObj.checkedKeys;
      this.detail.showMenus = this.$refs.tree.getCheckedKeys();
      console.log(this.detail.showMenus);
    },
    //  数据权限更改
    currentCheckedData(nodeObj, SelectedObj) {
      // console.log(SelectedObj);
      // console.log(SelectedObj.checkedKeys); // 这是选中的节点的key数组
      // console.log(SelectedObj.checkedNodes); // 这是选中的节点数组\
      let list = [];
      SelectedObj.checkedNodes.forEach((item, index) => {
        if (!item.tableCode) {
          list.push(item.id);
        }
      });
      this.detail.hiddenTableFields = list;
    },
    // 提交
    createDetail(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let hintText = this.nameType == '新增' ? `新增${this.detail.name}` : `修改${this.detail.name}`;
          this.hint('create', hintText);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 确认提示
    hint(status, hintText, row) {
      this.$confirm(`${hintText}, 是否确认?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          switch (status) {
            case 'create':
              // console.log(this.detail);
              this.submitBrand(row);
              break;
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    // 提交接口
    async submitBrand() {
      let showMenus = this.$refs.tree.getCheckedKeys();
      showMenus = showMenus.concat(this.$refs.tree.getHalfCheckedKeys());
      let hiddenTableFields = this.$refs.treeData.getCheckedKeys();
      hiddenTableFields = hiddenTableFields.concat(this.$refs.treeData.getHalfCheckedKeys());
      const res = this.nameType == '新增' ? await rolesAdd({
        ...this.detail,
        showMenus,
        hiddenTableFields
      }) : await rolesUpdate({
        ...this.detail,
        id: this.$route.query.id,
        showMenus,
        hiddenTableFields
      });
      this.$notification('操作成功', 'success', res.msg);
      // console.log(res);
      this.returnUpper();
    },
    // 提交按钮
    confirm() { },
    // 取消按钮
    closeDialog() { },
    // 返回
    returnUpper() {
      this.$store.dispatch('tagsView/delView', this.$route);
      this.$router.back();
    }
  }
};
</script>

<style lang="scss" scoped>
.add {
  background: #fff;
  .addOrderPopout {
    height: 80vh;
    overflow: hidden;
    overflow-y: auto;
  }
  .input {
    width: 100%;
  }
  .el-form-item {
    margin-bottom: 16px;
    // width: 30%;
    ::v-deep.el-form-item__label {
      padding-bottom: 0;
      width: 20%;
      text-align: right;
    }
  }
  ::v-deep.el-dialog {
    height: calc(100vh - 80px);
    overflow-y: auto;
  }
  ::v-deep.el-dialog__body {
    padding: 0 20px 100px;
    position: relative;
  }
}

.el-form {
  display: flex;
  flex-wrap: wrap;
}
.el-form-item {
  width: 32%;
}
.range.el-form-item {
  width: 64%;
}
.tabBox {
  border-radius: 6px;
  overflow: hidden;
  div {
    width: 50%;
    background: #e9e9e9;
    // color: #fff;
    text-align: center;
    line-height: 36px;
    font-weight: bold;
    font-size: 14px;
    transition: all 0.6s;
  }
  .active {
    background: #8b2e2f;
    color: #fff;
  }
}
.footer {
  position: absolute;
  right: 50px;
  bottom: 80px;
}
::v-deep.el-form-item--mini .el-form-item__content,
::v-deep.el-form-item--mini .el-form-item__label {
  margin-left: 0 !important;
}
::v-deep.el-form-item--mini .el-form-item__error {
  padding-left: 50px !important;
}
.distribution {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 10px;
  span {
    font-weight: normal;
    color: #999;
  }
}
.rollBox {
  overflow-y: auto;
  height: 56vh;
  padding-bottom: 80px;
}
</style>
